package com.wx.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.wx.core.process.WxApi;
import com.wx.core.vo.FansGroup;
import com.wx.entity.SysWxuser;
import com.wx.entity.WxFansGroup;
import com.wx.entity.WxFansGroupExample;
import com.wx.service.SysWxTokenService;
import com.wx.service.SysWxuserService;
import com.wx.service.WxFansGroupService;
import com.wx.util.JsonUtil;
import com.wx.validate.RegexUtils;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.util.HttpUtils;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;
import com.zyht.wechat.framework.env.WechatEnv;

@Controller
@RequestMapping("admin/fansGroup")
public class WxFansGroupController extends AbsManageBaseController {

	private static final Logger logger = LoggerFactory.getLogger(WxFansGroupController.class);

	@Resource
	private SysWxTokenService sysWxTokenService;

	@Resource
	private WxFansGroupService wxFansGroupService;

	@Resource
	private SysWxuserService sysWxuserService;

	@Value("#{propertiesReader[session_wx_key]}")
	private String session_wx_key;

	@Value("#{propertiesReader[session_user_key]}")
	private String sessionKey;

	@RequestMapping(value = "/index")
	public String index(Integer currentPage,Model model,HttpServletRequest request){

		String wxid = getWxId(request);
		WxFansGroupExample exp = new WxFansGroupExample();
		exp.createCriteria().andWxidEqualTo(wxid);
		int total = this.wxFansGroupService.countByExample(exp);
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.parseInt(pageSizeStr);
		if(null == currentPage || 0 == currentPage)
			currentPage = 1;
		PageHelper.startPage(currentPage,pageSize);
		List<WxFansGroup> relist = wxFansGroupService.selectByExample(exp);
		Page<WxFansGroup> page = new Page<WxFansGroup>(total,currentPage,pageSize);
		page.setRecordList(relist);
		model.addAttribute("page",page);
		return "crm/group";
	}

	@RequestMapping(value = "/syncGroup",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String syncGroup(Model model,HttpServletRequest request,HttpSession session){

		SysWxuser sysWxuser = WechatEnv.wxuser;

		String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(),sysWxuser.getAppid(),sysWxuser.getAppsecretd());
		if(StringUtils.isEmpty(accessToken)){
			model.addAttribute("msg","公众丢失授权绑定");
			model.addAttribute("redirect","admin/sysuser/list");
			return "message";
		}
		// 分组列表
		String requestUrl = WxApi.getRequestUrl(WxApi.GET_GROUP_LIST,accessToken);
		String result = HttpUtils.httpsGet(requestUrl);
		JSONObject jsonObject = JSONObject.parseObject(result);
		logger.debug("******分组数据*********" + jsonObject.toString());
		// {"groups":[{"id":0,"name":"未分组","count":179},{"id":1,"name":"黑名单","count":0},{"id":2,"name":"星标组","count":0},{"id":100,"name":"一组","count":0},{"id":101,"name":"二组","count":0}]}
		@SuppressWarnings("unchecked")
		ArrayList<FansGroup> list = (ArrayList<FansGroup>) JsonUtil.str2list(jsonObject.getJSONArray("groups").toString(),FansGroup.class);
		wxFansGroupService.deleteAndInsert(sysWxuser.getWxid(),sysWxuser.getId(),list);

		model.addAttribute("msg","同步分组成功");
		model.addAttribute("redirect","admin/fansGroup/index");
		return "message";
	}

	@RequestMapping("toadd")
	public String toadd(){

		return "crm/addGroup";
	}

	@RequestMapping("toedit")
	public String toedit(@RequestParam(value = "id",required = true) final String id,HttpServletRequest request,HttpServletResponse response){

		WxFansGroup wxFansGroup = wxFansGroupService.selectByPrimaryKey(Integer.valueOf(id));
		request.setAttribute("wxFansGroup",wxFansGroup);
		return "crm/editGroup";
	}

	@RequestMapping("edit")
	public String edit(@RequestParam(value = "id",required = true) final String id,@RequestParam(value = "name",required = true) final String name,
		@RequestParam(value = "intro",required = true) final String intro,Model model,HttpServletRequest request,HttpServletResponse response,
		HttpSession session){

		SysWxuser sysWxuser = WechatEnv.wxuser;
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser.getWxid(),sysWxuser.getAppid(),sysWxuser.getAppsecretd());
		if(StringUtils.isEmpty(accessToken)){
			model.addAttribute("msg","公众丢失授权绑定");
			model.addAttribute("redirect","admin/sysuser/list");
			return "message";
		}
		WxFansGroup wxFansGroup = wxFansGroupService.selectByPrimaryKey(Integer.valueOf(id));
		wxFansGroup.setName(name);
		wxFansGroup.setGroupDesc(intro);
		wxFansGroupService.update(accessToken,wxFansGroup);
		model.addAttribute("msg","编辑分组成功");
		model.addAttribute("redirect","admin/fansGroup/index");
		return "message";
	}

	@RequestMapping(value = "/add",method = RequestMethod.POST)
	public String add(@RequestParam(value = "name",required = true) final String name,@RequestParam(value = "intro",required = true) final String intro,
		Model model,HttpServletRequest request,HttpSession session){

		if(RegexUtils.isNull(name)){
			logger.debug("名称不能为空");
			model.addAttribute("msg","名称不能为空");
			model.addAttribute("redirect","admin/fansGroup/addGroup");
			return "message";
		}

		String wxid = getWxId(request);
		SysUser session_user = getSessionUser(request);
		SysWxuser sysWxuser = sysWxuserService.selectByWxid(wxid);
		String accessToken = sysWxTokenService.getAccessToken(wxid,sysWxuser.getAppid(),sysWxuser.getAppsecretd());
		if(StringUtils.isEmpty(accessToken)){
			model.addAttribute("msg","公众丢失授权绑定");
			model.addAttribute("redirect","admin/sysuser/list");
			return "message";
		}
		WxFansGroup wxFansGroup = new WxFansGroup();
		wxFansGroup.setCount(0);
		wxFansGroup.setCreateTime(new Date());
		wxFansGroup.setGroupDesc(intro);
		wxFansGroup.setName(name);
		wxFansGroup.setUid(session_user.getId());
		wxFansGroup.setUpdateTime(new Date());
		wxFansGroup.setWxid(wxid);
		wxFansGroupService.create(accessToken,wxFansGroup);
		model.addAttribute("msg","添加分组成功");
		model.addAttribute("redirect","admin/fansGroup/index");
		return "message";
	}

	@RequestMapping(value = "delete",method = RequestMethod.GET)
	public String delete(@RequestParam(value = "id",required = true) final Integer id,Model model,HttpServletRequest request,HttpServletResponse response){

		if(id == null || id == 0){
			model.addAttribute("msg","删除节点参数错误");
			model.addAttribute("redirect","admin/fansGroup/index");
		}
		// 删除微信端分组
		WxFansGroup wxFansGroup = wxFansGroupService.selectByPrimaryKey(id);
		SysWxuser sysWxuser = WechatEnv.wxuser;
		String accessToken = sysWxTokenService.getAccessToken(sysWxuser);
		wxFansGroupService.deleteByGroupId(accessToken,wxFansGroup);
		model.addAttribute("msg","删除分组成功");
		model.addAttribute("redirect","admin/fansGroup/index");
		return "message";
	}
}
